/*
 * Copyright (c) 2018 - 2028. www.vtuzx.com Inc. All Rights Reserved
 */
package com.vtuzx.kingdee.xqc_api.service.proxy;

import com.vtuzx.core.VtuzxException;
import com.vtuzx.core.bean.dto.VtuzxMap;
import com.vtuzx.core.bean.dto.VtuzxPage;
import com.vtuzx.core.bean.dto.VtuzxToken;
import com.vtuzx.core.constant.IVtuzxConst;
import com.vtuzx.core.utils.VtuzxUtil;
import com.vtuzx.fast.dao.setting.CharacterDao;
import com.vtuzx.fast.service.impl.FastSettingServiceImpl;
import com.vtuzx.fast.utils.FastUtil;
import com.vtuzx.kingdee.xqc_core.dao.*;
import com.vtuzx.web.dao.mongo.CustomerDao;
import org.bson.Document;
import org.bson.types.ObjectId;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.mongodb.core.query.Criteria;
import org.springframework.stereotype.Service;

import java.util.*;

/**
 * Fast标准服务
 */
@Service
public class XqcSettingServiceImpl extends FastSettingServiceImpl {

    @Autowired
    private StockDao stockDao;

    @Autowired
    private StockDetailDao stockDetailDao;

    @Autowired
    private MaterialDao materialDao;

    @Autowired
    private DepartmentDao departmentDao;

    @Autowired
    private EmpInfoDao empInfoDao;

    @Autowired
    private CustomerDao customerDao;

    @Autowired
    private CharacterDao characterDao;

    public void addCustomer(VtuzxToken token, Map<String, Object> param) throws VtuzxException {
        String account = VtuzxUtil.getString(param, "account");
        long cnt = this.customerDao.count(Criteria.where("account").is(account));
        if (cnt > 0L) {
            throw new VtuzxException("E_account_exist");
        } else {
            String password = VtuzxUtil.md5(VtuzxUtil.getString(param, "password"));
            this.customerDao.insertOne(this.parseCustomerUpdate(token, param)
                    .append("password", password)
                    .append("stockNos", VtuzxUtil.getObject(param, "stockNos"))
                    .append("department", VtuzxUtil.getString(param, "department")));
        }
    }

    public void updateCustomer(VtuzxToken token, Map<String, Object> param) throws VtuzxException {
        ObjectId _id = FastUtil.convertId(VtuzxUtil.getString(param, "id"));
        String account = VtuzxUtil.getString(param, "account");
        long cnt = this.customerDao.count(Criteria.where("_id").ne(_id).and("account").is(account));
        if (cnt > 0L) {
            throw new VtuzxException("E_account_exist");
        } else {
            this.customerDao.updateById(_id, this.parseCustomerUpdate(token, param)
                    .append("stockNos", VtuzxUtil.getObject(param, "stockNos"))
                    .append("department", VtuzxUtil.getString(param, "department")));
        }
    }

    private Document parseCustomerUpdate(VtuzxToken token, Map<String, Object> param) {
        List<String> characterIds = VtuzxUtil.getObject(param, "characterIds");
        List<String> organizationIds = VtuzxUtil.getObject(param, "organizationIds");
        List<String> positionIds = VtuzxUtil.getObject(param, "positionIds");
        return (new Document("account", VtuzxUtil.getString(param, "account"))).append("name", VtuzxUtil.getString(param, "name")).append("nickName", VtuzxUtil.getString(param, "nickName")).append("_characterIds", FastUtil.convertId(characterIds)).append("_organizationIds", FastUtil.convertId(organizationIds)).append("_positionIds", FastUtil.convertId(positionIds)).append("gender", VtuzxUtil.getString(param, "gender")).append("birthday", VtuzxUtil.parseDate(VtuzxUtil.getString(param, "birthday"))).append("mobile", VtuzxUtil.getString(param, "mobile")).append("email", VtuzxUtil.getString(param, "email"));
    }


    public VtuzxMap getCustomer(VtuzxToken token, Map<String, Object> param) {
        int pageIndex = VtuzxUtil.getInt(param, "pageIndex");
        int pageSize = VtuzxUtil.getInt(param, "pageSize", 20);
        Criteria cond = new Criteria();
        boolean isSuperRole = VtuzxUtil.getBoolean(token, "isSuperRole");
        if (!isSuperRole) {
            VtuzxPage page = this.characterDao.page(Criteria.where("isSuperRole").is(true), (Document)null, 0, 0);
            if (page.total() != 0L) {
                List<ObjectId> _organizationIds = page.iterator((doc) -> doc.getObjectId(IVtuzxConst.Key__id));
                cond.and("_characterIds").nin(_organizationIds);
            }
        }

        String searchKey = VtuzxUtil.getString(param, "keyword");
        if (!VtuzxUtil.isEmpty(searchKey)) {
            cond.orOperator(Criteria.where("account").regex("^.*" + searchKey + ".*$"), Criteria.where("name").regex("^.*" + searchKey + ".*$"), Criteria.where("nickName").regex("^.*" + searchKey + ".*$"));
        }

        List<String> organizationIds = VtuzxUtil.getObject(param, "organizationIds");
        if (organizationIds != null && organizationIds.size() > 0) {
            cond.and("_organizationIds").in(FastUtil.convertId(organizationIds));
        }

        VtuzxPage page = this.customerDao.page(cond, new Document("createTime", -1), pageIndex, pageSize);
        long total = page.total();
        if (total == 0L) {
            return (new VtuzxMap("total", total)).append("data", new ArrayList<>());
        } else {
            List<VtuzxMap> customerList = page.iterator((doc) -> {
                List<ObjectId> characterIds = VtuzxUtil.getObject(doc, "_characterIds");
                List<ObjectId> _organizationIds = VtuzxUtil.getObject(doc, "_organizationIds");
                List<ObjectId> positionIds = VtuzxUtil.getObject(doc, "_positionIds");
                return (new VtuzxMap("id", doc.getObjectId("_id").toString())).append("stockNos", VtuzxUtil.getObject(doc, "stockNos")).append("department", VtuzxUtil.getString(doc, "department")).append("account", VtuzxUtil.getString(doc, "account")).append("name", VtuzxUtil.getString(doc, "name")).append("nickName", VtuzxUtil.getString(doc, "nickName")).append("isLock", VtuzxUtil.getBoolean(doc, "isLock")).append("characterIds", FastUtil.convertStrId(characterIds)).append("organizationIds", FastUtil.convertStrId(_organizationIds)).append("positionIds", FastUtil.convertStrId(positionIds)).append("gender", VtuzxUtil.getString(doc, "gender")).append("birthday", VtuzxUtil.formatYmdF((Date)VtuzxUtil.getObject(doc, "birthday"))).append("mobile", VtuzxUtil.getString(doc, "mobile")).append("email", VtuzxUtil.getString(doc, "email"));
            });
            return (new VtuzxMap("total", total)).append("data", customerList);
        }
    }

    /**
     * 增加字典数据
     *
     * @param param 字典数据
     * @return 字典数据
     */
    @Override
    public VtuzxMap getOptions(VtuzxToken token, Map<String, Object> param) {
        List<String> keys = VtuzxUtil.getObject(param, "keys");
        VtuzxMap res = new VtuzxMap();

        if (keys.contains("stock")) {
            keys.remove("stock");
            //取仓库
            Iterator<Document> stockItr = stockDao.findList(null, new Document("fNumber", 1), 0, 0);
            List<VtuzxMap> stockList = new ArrayList<>();
            while (stockItr.hasNext()) {
                Document stockDoc = stockItr.next();
                String fName = VtuzxUtil.getString(stockDoc, "fName");
                String fNumber = VtuzxUtil.getString(stockDoc, "fNumber");
                stockList.add(new VtuzxMap("key", fNumber).append("name", fName));
            }
            res.append("stock", stockList);
        }
        if (keys.contains("location")) {
            keys.remove("location");
            //取仓位
            Iterator<Document> stockDetailItr = stockDetailDao.findList(null, new Document("fNumber", 1), 0, 0);
            List<VtuzxMap> stockDetailList = new ArrayList<>();
            while (stockDetailItr.hasNext()) {
                Document stockDetailDoc = stockDetailItr.next();
                String locationName = VtuzxUtil.getString(stockDetailDoc, "locationName");
                String locationNo = VtuzxUtil.getString(stockDetailDoc, "locationNo");
                stockDetailList.add(new VtuzxMap("key", locationNo).append("name", locationName));
            }
            res.append("stockDetail", stockDetailList);
        }
        if (keys.contains("unit")) {
            keys.remove("unit");
            //取仓位
            Iterator<Document> unitItr = materialDao.findList(null, new Document("fNumber", 1), 0, 0);
            List<VtuzxMap> unitList = new ArrayList<>();
            while (unitItr.hasNext()) {
                Document unitDoc = unitItr.next();
                String fBaseUnitIdFName = VtuzxUtil.getString(unitDoc, "fBaseUnitIdFName");
                String fBaseUnitIdNumber = VtuzxUtil.getString(unitDoc, "fBaseUnitIdNumber");
                unitList.add(new VtuzxMap("key", fBaseUnitIdNumber).append("name", fBaseUnitIdFName));
            }
            res.append("unit", unitList);
        }
        if (keys.contains("material")) {
            keys.remove("material");
            //取仓位
            Iterator<Document> unitItr = materialDao.findList(null, new Document("fNumber", 1), 0, 0);
            List<VtuzxMap> materialList = new ArrayList<>();
            while (unitItr.hasNext()) {
                Document unitDoc = unitItr.next();
                String fNumber = VtuzxUtil.getString(unitDoc, "fNumber");
                String fName = VtuzxUtil.getString(unitDoc, "fName");
                materialList.add(new VtuzxMap("key", fNumber).append("name", fName));
            }
            res.append("material", materialList);
        }
        if (keys.contains("department")) {
            keys.remove("department");
            //取部门
            Iterator<Document> unitItr = departmentDao.findList(null, new Document("fNumber", 1), 0, 0);
            List<VtuzxMap> departmentList = new ArrayList<>();
            while (unitItr.hasNext()) {
                Document unitDoc = unitItr.next();
                String fNumber = VtuzxUtil.getString(unitDoc, "fNumber");
                String fDeptId = VtuzxUtil.getString(unitDoc, "fDeptId");
                String fName = VtuzxUtil.getString(unitDoc, "fName");
                departmentList.add(new VtuzxMap("key", fNumber).append("name", fName).append("fDeptId", fDeptId));
            }
            res.append("department", departmentList);
        }
        if (keys.contains("empInfo")) {
            keys.remove("empInfo");
            //取员工
            Iterator<Document> unitItr = empInfoDao.findList(null, new Document("fNumber", 1), 0, 0);
            List<VtuzxMap> empInfoList = new ArrayList<>();
            while (unitItr.hasNext()) {
                Document unitDoc = unitItr.next();
                String fNumber = VtuzxUtil.getString(unitDoc, "fNumber");
                String fName = VtuzxUtil.getString(unitDoc, "fName");
                String fPostEntity_FPostDept = VtuzxUtil.getString(unitDoc, "fPostEntity_FPostDept");
                empInfoList.add(new VtuzxMap("key", fNumber).append("name", fName).append("fPostDept", fPostEntity_FPostDept));
            }
            res.append("empInfo", empInfoList);
        }
        VtuzxMap superRes = super.getOptions(param);
        res.putAll(superRes);
        return res;
    }

}
